package com.open.capacity.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysDict;
import com.open.capacity.user.service.SysDictService;
import com.open.capacity.user.vo.SysDictDataVo;
import com.open.capacity.utils.encrypt.Md5Utils;
import com.open.capacity.vo.MapVo;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.list.TreeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 字典管理
 */
@RestController
@Api(tags = "字典模块api")
public class SysDictController {

    private static Logger logger = LoggerFactory.getLogger(SysDictController.class);


    @Autowired
    private SysDictService dictService;


    /**
     * 查询字典
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "查询字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父级id", dataType = "String"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "String")
    })
    @GetMapping("/dicts")
    public Result<List<SysDict>> findAreas(@RequestParam Map<String, Object> params) {
        List<SysDict> list = dictService.findDicts(params);
        return Result.succeed(list);
    }

    /**
     * 查询字典tree
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "查询字典tree")
    @GetMapping("/dicts/tree")
    public Result<List<TreeVo>> treeAreas(@RequestParam(value = "parentId", required = false) String parentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", parentId);
        List<SysDict> dicts = dictService.findDicts(params);
        List<TreeVo> treeList = new TreeList();
        dicts.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getName());
            node.setValue(m.getCode());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(true);
            node.setComplete(true);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });
        return Result.succeed(TreeVo.RecursiveBuilder(treeList));
    }


    /**
     * 查询字典map
     *
     * @param ver
     * @return
     */
    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "查询字典map")
    @GetMapping("/dicts/map")
    public Result<MapVo> mapDicts(@RequestParam(value = "ver", required = false) String ver) {
        Map<String, Map<String, SysDictDataVo>> dictMaps = dictService.getMap();
        MapVo<Map<String, Map<String, SysDictDataVo>>> vo = new MapVo();
        vo.setData(dictMaps);
        vo.setVer(Md5Utils.hash(JSONObject.toJSONString(dictMaps)));
        return Result.succeed(vo);
    }


    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "判断字典name是否存在")
    @GetMapping("/dicts/existsName")
    public Result existsName(@RequestParam(value = "name") String name) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        List<SysDict> list = dictService.findDicts(params);
        return Result.succeed(CollectionUtils.isNotEmpty(list));
    }

    @PreAuthorize("hasAuthority('dict:get/dicts')")
    @ApiOperation(value = "判断字典name是否存在")
    @GetMapping("/dicts/existsCode")
    public Result existsCode(@RequestParam(value = "code") String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        List<SysDict> list = dictService.findDicts(params);
        return Result.succeed(CollectionUtils.isNotEmpty(list));
    }


    /**
     * 字典新增或者更新
     *
     * @param sysDict
     * @return
     */
    @PreAuthorize("hasAnyAuthority('dict:post/dicts','dict:put/dicts')")
    @ApiOperation(value = "保存字典")
    @PostMapping("/dicts/saveOrUpdate")
    @LogAnnotation(module = "数据字典", name = "更新")
    public Result saveOrUpdate(@RequestBody SysDict sysDict, String keyValue) {
        return dictService.saveOrUpdate(sysDict, keyValue);
    }


    /**
     * 删除字典
     * delete /dicts/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('dict:delete/dicts/{id}')")
    @ApiOperation(value = "删除字典")
    @DeleteMapping("/dicts/{id}")
    @LogAnnotation(module = "数据字典", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            dictService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }
}
